package com.finger.forest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Configuration;
import android.database.Cursor;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseApi;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.encode.PrefsUtil;

import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 自动拍照 （SOS）
 */
public class AutoPhotoActivity extends BaseActivity<RegisterPresenter> implements SurfaceHolder.Callback, Camera.PictureCallback,
        BaseView {

    private static final String CAMERA_CONTROLL = "CAMERA_CONTROLL";

    @BindView(R.id.surfaceView)
    SurfaceView surfaceView;

    private Camera camera;

    private SurfaceHolder surfaceHolder;

    private Handler timerUpdateHandler;
    private boolean timerRunning = false;
    private int currentTimer = 10;
    private static int RUN_time = 2000;//2秒钟拍一次

    private List<File> files = new ArrayList<>();

    @Override
    protected int setView() {
        return R.layout.activity_auto_photo;
    }

    @Override
    protected void receiveData() {

    }

    @Override
    protected void initializeView() {
        surfaceHolder = surfaceView.getHolder();

        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        surfaceHolder.addCallback(this);

        timerUpdateHandler = new Handler();

        thread.start();
    }

    @Override
    protected void loadDataFromServer() {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        int cameraNums = Camera.getNumberOfCameras();
        Log.e(CAMERA_CONTROLL, cameraNums + "");
        try {
            //  camera = Camera.open(cameraNums - 1);
            camera = Camera.open(0);
        } catch (Exception e) {
            Log.e(CAMERA_CONTROLL, e.getMessage());
        }
        try {
            camera.setPreviewDisplay(holder);
            Camera.Parameters parameters = camera.getParameters();
            if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                parameters.set("orientation", "portrait");
                camera.setDisplayOrientation(90);
                parameters.setRotation(90);
            }
            List<String> colorEffects = parameters.getSupportedColorEffects();
            Iterator<String> cei = colorEffects.iterator();
            while (cei.hasNext()) {
                String currentEffect = cei.next();
                if (currentEffect.equals(Camera.Parameters.EFFECT_SOLARIZE)) {
                    parameters
                            .setColorEffect(Camera.Parameters.EFFECT_SOLARIZE);
                    break;
                }
            }
            camera.setParameters(parameters);
        } catch (Exception e) {
            // e.printStackTrace();
            camera.release();
        }
    }


    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            int i = 1;
            while (i > 0) {
                i--;
                try {
                    Thread.sleep(RUN_time);

                    currentTimer = 2;
                    if (!timerRunning) {
                        timerRunning = true;
                        timerUpdateHandler.post(timerUpdateTask);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    });


    private Runnable timerUpdateTask = new Runnable() {

        @Override
        public void run() {
            if (currentTimer > 1) {
                currentTimer--;
                timerUpdateHandler.postDelayed(timerUpdateTask, 1000);
            } else {
                camera.takePicture(null, null, null, AutoPhotoActivity.this);
                timerRunning = false;
                currentTimer = 10;
            }
        }
    };

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        camera.startPreview();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        camera.stopPreview();
        camera.release();
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        Uri imageFileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());

        //我添加的
        String pathpicture = getRealFilePath(AutoPhotoActivity.this, imageFileUri);
        Log.e("PicDir", pathpicture);
        ToastUtils.show("拍照成功");

        File file = new File(pathpicture);
        luBan(file);

        try {
            OutputStream imageFileOS = getContentResolver().openOutputStream(
                    imageFileUri);

            imageFileOS.write(data);
            imageFileOS.flush();
            imageFileOS.close();

        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
        camera.startPreview();
    }

    private void luBan(File imgFile) {
        Luban.with(this)
                .load(imgFile)
                .ignoreBy(100)
                .filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")))
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // 压缩开始前调用，可以在方法内启动 loading UI
                        Log.e("onStart", "onStart");
                    }

                    @Override
                    public void onSuccess(File file) {
                        // 压缩成功后调用，返回压缩后的图片文件
                        files.add(file);

//                        if (files.size() == 4) {
                            Map<String, RequestBody> bodyMap = new HashMap<>();
                            bodyMap.put("longitude", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), PrefsUtil.getString(AutoPhotoActivity.this, CommonKey.LOCATION_LONGITUDE)));

                            bodyMap.put("latitude", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), PrefsUtil.getString(AutoPhotoActivity.this, CommonKey.LOCATION_LATITUDE)));
                            bodyMap.put("terminalId", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), drUid + ""));

                            List<MultipartBody.Part> partMap = new ArrayList<>();

                            for (File f : files) {
                                RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), f);
                                MultipartBody.Part requestImgPart =
                                        MultipartBody.Part.createFormData("imageFile", f.getPath(), requestFile);
                                partMap.add(requestImgPart);
                            }
                            showPd();
                            presenter.uploadSos(bodyMap, partMap);
//                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        // 当压缩过程出现问题时调用
                        Log.e("Throwable", e.getMessage());
                    }
                }).launch();
    }

    //我添加的
    String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            case ResponseTag.UPLOAD_SOS:
                ToastUtils.show(msg);
                finish();
                break;
        }
        hidePd();
    }

    @Override
    public void onError(int errcode, int tag, String message) {
        hidePd();
        ToastUtils.show(message == null ? "sos求救失败" : message);
    }
}